<template>
  <el-dialog
    :model-value="props.accountingPlanVisible"
    title="核算方案选择"
    width="70%"
    :before-close="handleClose"
  >
    <div class="ele-type">
      <fieldset class="ele-type-item1">
        <legend>核算方案:</legend>
        <div class="ele-type-item11">
          <el-table
            highlight-current-row
            :data="sAccountData"
            height="450"
            @row-click="rowClick"
          >
            <el-table-column prop="name" label="" />
          </el-table>
        </div>
        <div class="ele-type-item12">
          <el-button @click="addSAccount">新增</el-button>
          <el-button @click="delSAccount">删除</el-button>
        </div>
      </fieldset>
      <fieldset class="ele-type-item2">
        <legend>电价:</legend>
        <div class="ele-type-item21">
          <el-table
            highlight-current-row
            :data="sElePriceData"
            @row-click="changeElePrice"
            height="450"
            ref="sElePriceRef"
          >
            <el-table-column prop="formula" label="公式描述" />
          </el-table>
        </div>
        <div class="ele-type-item22">
          <el-button @click="addSElePrice">新增</el-button>
          <el-button @click="delSElePrice">删除</el-button>
          <!-- <el-button @click="clearSElePrice">清除</el-button> -->
          <el-button @click="ascSElePrice">
            <el-icon><Top /></el-icon>
          </el-button>
          <el-button @click="descSElePrice">
            <el-icon><Bottom /></el-icon>
          </el-button>
          <el-button @click="saveSElePrice">保存</el-button>
        </div>
      </fieldset>
      <fieldset class="ele-type-item3">
        <legend>公式编辑:</legend>
        <div class="ele-type-item31">
          <el-tabs type="border-card">
            <div>
              <el-tab-pane label="变量">
                <div class="ele-type-item3-1">
                  <fieldset class="ele-type-item3-11">
                    <legend>已知变量:</legend>
                    <div>
                      <el-table
                        :data="knownVariables"
                        @row-dblclick="changeKnowVariable"
                        height="260"
                      >
                        <el-table-column prop="name" label="" />
                      </el-table>
                    </div>
                  </fieldset>
                  <fieldset class="ele-type-item3-12">
                    <legend>固定变量:</legend>
                    <div>
                      <el-table
                        highlight-current-row
                        :data="fixedVariableData"
                        @row-dblclick="changeVariable"
                        height="260"
                      >
                        <el-table-column prop="label" label="" />
                      </el-table>
                    </div>
                  </fieldset>
                </div>
              </el-tab-pane>
              <el-tab-pane label="说明">
                <div style="height: 280px">
                  <p>说明:</p>
                  <p>=:赋值</p>
                  <p>+:加法</p>
                  <p>-:减法</p>
                  <p>*:乘法</p>
                  <p>/:除法</p>
                  <p>():括号，调整运算顺序</p>
                  <p>^次方操作。如:平方用^2</p>
                  <p>开平方用^0.5表示</p>
                  <p>尽量用0限制运算顺序</p>
                  <p>例如:A=(B*C)^2+D和A=B*C^(2+D)</p>
                  <p>运算的结果是不一样的。</p>
                  <p>例:视在功率=(有功功率^2+无功功率^2)^0.5</p>
                </div>
              </el-tab-pane>
            </div>
          </el-tabs>
        </div>
        <div class="ele-type-item32">
          <div class="ele-type-item32-1">
            <el-input class="desc" v-model="desc" type="textarea" />
          </div>
          <div class="ele-type-item32-2">
            <el-button @click="saveElePrice">确定</el-button>
          </div>
        </div>
      </fieldset>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">返回</el-button>
        <el-button type="primary" @click="handle"> 确定 </el-button>
      </span>
    </template>
    <!-- 新增方案 -->
    <sAccountDialog
      @is-show="isShow"
      @doAddSAccount="doAddSAccount"
      :sAccountVisible="sAccountVisible"
      :form="form"
    ></sAccountDialog>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, onMounted } from "vue";
import { fixedVariableData } from "@/gm/comm.js";
import { useAppStore } from "@/stores";
import { storeToRefs } from "pinia";
const useApp = useAppStore();
let { currentAccountingData } = storeToRefs(useApp);
import {
  sAccountingPlanList,
  sAccountingPlanSave,
  sAccountingPlanRemove,
  sElectricityPriceFormulaList,
  sElectricityPriceFormulaUpdate,
  sElectricityPriceFormulaSave,
  sElectricityPriceFormulaRemove,
  sElectricityPriceFormulaChangeSort,
} from "@/api/app.js";

const emit = defineEmits(["is-show", "calculateFormula"]);
const num = ref(1);
const sAccountData = ref([]);
const sElePriceData = ref([]);
const currentData = ref([]);
const sAccountVisible = ref(false);
const accountingPlanId = ref();
const formulaInfo = ref("");
const knownVariables = ref([]);
const keysArr = ref([]);
const valuesArr = ref([]);

const form = reactive({
  name: "",
});
const sElePriceRef = ref();

const props = defineProps({
  accountingPlanVisible: Boolean,
  position: String,
});
const tableData = ref([]);
const desc = ref("");
const currentRow = ref([]);
const flag = ref(false);
//数据初始化
onMounted(() => {
  init();
});
//获取核算方案列表
const init = async () => {
  await sAccountingPlanList()
    .then((res) => {
      sAccountData.value = res.data;
      // console.log(res);
    })
    .catch((err) => {
      console.log(err);
    });
};
// 核算方案点击事件
const rowClick = async (row, type) => {
  console.log("rowClick", row);
  let parm = {
    accountingPlanId: row.id,
  };
  accountingPlanId.value = row.id;
  //电价排序判断 参数1删除2正向3反向4新增
  let arr = [1, 2, 3, 4];
  if (arr.includes(type)) {
    parm = {
      accountingPlanId: row.accountingPlanId,
    };
    accountingPlanId.value = row.accountingPlanId;
  } else {
    currentRow.value = row;
  }
  await sElectricityPriceFormulaList(parm)
    .then((res) => {
      sElePriceData.value = res.data;
      currentAccountingData.value[props.position] = res.data;
      //设置默认选中行
      if (row.sort) {
        if (type === 3) {
          sElePriceRef.value.setCurrentRow(sElePriceData.value[0]);
          currentData.value = sElePriceData.value[0]; //点击当前选中数据
        } else {
          let temData = [];
          temData = sElePriceData.value.filter((item) => item.id === row.id);
          sElePriceRef.value.setCurrentRow(temData[0]);
          currentData.value = temData[0]; //点击当前选中数据
          changeElePrice(temData[0]); //模拟电价点击
          // console.log("temData", temData);
        }
      } else {
        sElePriceRef.value.setCurrentRow(sElePriceData.value[0]);
        currentData.value = sElePriceData.value[0]; //点击当前选中数据
      }
    })
    .catch((err) => {
      console.log(err);
    });
};
//新增方案
const addSAccount = () => {
  sAccountVisible.value = true;
  form.name = "";
};
//接口处理新增方案
const doAddSAccount = async (parm) => {
  await sAccountingPlanSave(parm)
    .then((res) => {
      sAccountVisible.value = false;
      init();
      ElMessage({
        message: "保存成功",
        type: "success",
      });
    })
    .catch(() => {
      ElMessage({
        message: "保存失败",
        type: "warning",
      });
    });
};
//删除方案
const delSAccount = async () => {
  let parm = {
    id: accountingPlanId.value,
  };
  await sAccountingPlanRemove(parm)
    .then((res) => {
      init();
      ElMessage({
        message: "删除成功",
        type: "success",
      });
    })
    .catch(() => {
      ElMessage({
        message: "删除失败",
        type: "warning",
      });
    });
};
//关闭弹窗
const isShow = () => {
  sAccountVisible.value = false;
};
//新增电价
const addSElePrice = async () => {
  let obj = {
    accountingPlanId: accountingPlanId.value,
  };
  await sElectricityPriceFormulaSave(obj)
    .then((res) => {
      rowClick(obj, 4); //更新列表
      ElMessage({
        message: "新增成功",
        type: "success",
      });
    })
    .catch((err) => {
      console.log(err);
      ElMessage({
        message: "新增失败",
        type: "warning",
      });
    });
};
//删除电价
const delSElePrice = async () => {
  let id;
  if (currentData.value.id) {
    id = currentData.value.id;
  } else {
    let num = sElePriceData.value.length - 1;
    id = sElePriceData.value[num].id;
  }
  let obj = {
    id,
  };
  await sElectricityPriceFormulaRemove(obj)
    .then((res) => {
      rowClick(currentData.value, 3);
      ElMessage({
        message: "删除成功",
        type: "success",
      });
    })
    .catch((err) => {
      console.log(err);
      ElMessage({
        message: "删除失败",
        type: "warning",
      });
    });
};
//清除电价
const clearSElePrice = () => {};
//正向排序
const ascSElePrice = async () => {
  let obj = {
    id: currentData.value.id,
    oper: "up",
  };

  if (
    currentData.value.id &&
    currentData.value.sort != sElePriceData.value[0].sort
  ) {
    await sElectricityPriceFormulaChangeSort(obj)
      .then((res) => {
        rowClick(currentData.value, 1); //模拟点击核算方案
      })
      .catch((err) => {
        console.log(err);
      });
  }
};
//反向排序
const descSElePrice = async () => {
  let obj = {
    id: currentData.value.id,
    oper: "down",
  };
  let num = sElePriceData.value.length;
  if (
    currentData.value.id &&
    currentData.value.sort != sElePriceData.value[num - 1].sort
  ) {
    await sElectricityPriceFormulaChangeSort(obj)
      .then((res) => {
        rowClick(currentData.value, 2);
      })
      .catch((err) => {
        console.log(err);
      });
  }
};
//编辑电价
const changeElePrice = (row) => {
  currentData.value = row;
  desc.value = currentData.value.formula;
  knownVariables.value = [];
  keysArr.value = [];
  valuesArr.value = [];
  sElePriceData.value.forEach((item) => {
    if (item.sort < row.sort) {
      item.name = item.formula.split("=")[0];
      item.content = item.formula.split("=")[1];
      knownVariables.value.push(item);
      keysArr.value.push(item.name);
      valuesArr.value.push(item.content);
    }
  });
  if (desc.value) saveElePrice(); //保存之前电价数据匹配
};
//固定变量点击
const changeVariable = (row) => {
  desc.value += row.label;
  if (formulaInfo.value) formulaInfo.value += "," + row.label;
  else formulaInfo.value = row.label;
};
const changeKnowVariable = (row) => {
  desc.value += row.name;
};
//保存修改电价信息
const saveElePrice = () => {
  currentData.value.formula = desc.value;
  let newStr = currentData.value.formula;
  // 遍历需要替换的字符列表
  for (let i = 0; i < keysArr.value.length; i++) {
    let charToReplace = keysArr.value[i];
    let replacementChar = "(" + valuesArr.value[i] + ")";
    // 使用正则表达式进行全局替换
    newStr = newStr.replace(new RegExp(charToReplace, "g"), replacementChar);
  }
  formulaInfo.value = newStr;
  flag.value = true;
};
const saveSElePrice = async () => {
  if (currentData.value.id) {
    let str = formulaInfo.value;
    let newStr = str.replaceAll(/\^2/g, "**2");
    newStr = newStr.replaceAll(/\^0.5/g, "**0.5");
    let parm = {
      accountingPlanId: currentData.value.accountingPlanId,
      formula: desc.value,
      formulaInfo: newStr,
      id: currentData.value.id,
    };

    await sElectricityPriceFormulaUpdate(parm)
      .then((res) => {
        // console.log(res);
        ElMessage({
          message: "保存成功",
          type: "success",
        });
      })
      .catch((err) => {
        console.log(err);
        ElMessage({
          message: "保存失败",
          type: "warning",
        });
      });
  }
};
const handleChange = (value) => {
  // console.log(value);
};
const handleClose = () => {
  emit("is-show");
};
const handle = () => {
  //参数1.方案数据
  emit("calculateFormula", currentRow.value);
  emit("is-show");
};
</script>
<style lang="scss" scoped>
.ele-type {
  display: flex;
  .ele-type-item1 {
    width: 230px;
    height: 550px;
    .ele-type-item11 {
      max-height: 500px;
      padding: 5px;
    }
    .ele-type-item12 {
      display: flex;
      justify-content: center;
      margin-top: 10px;
      .el-button {
        width: 80px;
      }
    }
  }
  .ele-type-item2 {
    width: 230px;
    height: 550px;
    .ele-type-item21 {
      max-height: 500px;
      padding: 5px;
    }
    .ele-type-item22 {
      display: flex;
      justify-content: center;
      margin-top: 10px;
      .el-button {
        width: 60px;
      }
    }
  }
  .ele-type-item3 {
    flex: 1;
    height: 550px;
    .ele-type-item31 {
      max-height: 500px;
      padding: 5px;
    }
    .ele-type-item32 {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 5px;
      .ele-type-item32-1 {
        width: 100%;
      }
      .ele-type-item32-2 {
        margin-top: 10px;
      }
      .el-button {
        width: 100px;
      }
    }
    .ele-type-item3-1 {
      display: flex;
      .ele-type-item3-11 {
        width: 160px;
      }
      .ele-type-item3-12 {
        flex: 1;
      }
    }
  }
}
.dialog-footer {
  display: flex;
  justify-content: center;
  .el-button {
    width: 60px;
  }
}
.desc {
  :deep(.el-textarea__inner) {
    //el_input中的隐藏属性
    resize: none; //禁止拉伸
    height: 120px !important;
  }
}
</style>
